<?php
/*
* This controller is responsible for processing all action of FrontAdminMenu
*/
class Backend_AjaxController extends RCMS_Core_BaseController {

    protected $_websiteUrl;

    protected $_smtpHost;

    protected $_smtpLogin;

    protected $_smtpPassword;

    protected $_adminEmail;

    protected $_smtpConfigArray;

    protected $_configTableArray;

    protected $_domain;

    protected $_pageUrl;

	protected $_seoParser = null;

    /**
     * This method loads each time when we call the class method.
     * @return void
     */
    public function init()
    {
        $this->_model = new Default_Model_AjaxModel();
        parent::init();
        $this->_websiteUrl = $this->_config->website->website->url;
		$this->_seoParser = new RCMS_Object_Parser_SeoParser();
    }

    /**
     * This is function inits smtp settings
     * @return void
     */
    private function _initSmtp()
    {
        $this->_domain = ($this->_smtpHost)? ucfirst($this->_smtpHost) : $this->_websiteUrl;
        $configArray = $this->_model->selectAllConfigSettings();
        if($configArray) {
            $this->_configTableArray = $configArray;
            if(isset($configArray['smtp_host']) && $configArray['smtp_host'] != ''){
                $this->_smtpHost = $configArray['smtp_host'];
            }
            if(isset($configArray['smtp_login']) && $configArray['smtp_login'] != ''){
                $this->_smtpLogin = $configArray['smtp_login'];
            }
            if(isset($configArray['smtp_password']) && $configArray['smtp_password'] != ''){
                $this->_smtpPassword = $configArray['smtp_password'];
            }
            if(isset($configArray['admin_email']) && $configArray['admin_email'] != ''){
                $this->_adminEmail = $configArray['admin_email'];
            }
            $this->_smtpConfigArray = array(
                'auth'      => 'login',
                'username'  => $this->_smtpLogin,
                'password'  => $this->_smtpPassword,
                'host'      => $this->_smtpHost
            );
        }
    }

    /**
     * This is function loads images for edit content.
     * @return void
     */
    function loadimagesforeditcontentAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        if($this->getRequest()->isPost() && $this->getRequest()->getParam('folder') !== ''){
            $folder = $this->getRequest()->getParam('folder');
            $textareaId = $this->getRequest()->getParam('textarea');
            $strImagesSmall = '';
            $strImagesMedium = '';
            $strImagesLarge = '';
            $strVideo = '';
            //got array images            
            $imagesSmall = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');
            $imagesMedium = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/medium/');
            $imagesLarge = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/large/');
            $videoFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/video/');
            $path = $this->view->websiteUrl . 'images/' . $folder . '/';
                //load small images
                if(!empty($imagesSmall) && is_array($imagesSmall)){
                    foreach ($imagesSmall as $imageSmall){
                        $elmSmallImage = "<a href=" . $path . "original/" . $imageSmall . " class=thickbox><img border=0 alt=" .  Default_View_Helper_ToolsHelper::cropType($imageSmall) . " src=" . $path . "small/" . $imageSmall . " /></a>";
                        $strImagesSmall .= "<a href=\\'javascript:;\\' onmousedown=\"$(\\'#" . $textareaId . "\\').tinymce().execCommand(\\'mceInsertContent\\',false, \\'" . $elmSmallImage . "\\');\">";
                        $strImagesSmall .= '<img title="' . $imageSmall . '" style="vertical-align:top; margin: 0px 0px 4px 4px;" border="0" width="65" src="' . $path . 'small/' . $imageSmall .'"></a>';
                    }
                }
                $this->view->strImagesSmall = $strImagesSmall . '<div style="clear:both;height:0px;">&nbsp;</div>';
		$this->_websiteUrl = $this->_config->website->website->url;
                //load medium images
                if(!empty($imagesMedium) && is_array($imagesMedium)){
                    foreach ($imagesMedium as $imageMedium){
                        $elmMediumImage = "<a href=" . $path . "original/" . $imageMedium . " class=thickbox><img border=0 alt=" .  Default_View_Helper_ToolsHelper::cropType($imageMedium) . " src=" . $path . "medium/" . $imageMedium . " /></a>";
                        $strImagesMedium .= "<a href=\\'javascript:;\\' onmousedown=\"$(\\'#" . $textareaId . "\\').tinymce().execCommand(\\'mceInsertContent\\',false, \\'" . $elmMediumImage . "\\');\">";
                        $strImagesMedium .= '<img style="vertical-align:top; margin: 0 0 4px 4px;" border="0" width="65" src="' . $path . 'small/' . $imageMedium .'"></a>';
                    }
                }
                $this->view->strImagesMedium = $strImagesMedium . '<div style="clear:both;height:0px;">&nbsp;</div>';

                //load large images
                if(!empty($imagesLarge) && is_array($imagesLarge)){
                    foreach ($imagesLarge as $imageLarge){
                        $elmLargeImage = "<a href=" . $path . "original/" . $imageLarge . " class=thickbox><img border=0 alt=" .  Default_View_Helper_ToolsHelper::cropType($imageLarge) . " src=" . $path . "large/" . $imageLarge . " /></a>";
                        $strImagesLarge .= "<a href=\\'javascript:;\\' onmousedown=\"$(\\'#" . $textareaId . "\\').tinymce().execCommand(\\'mceInsertContent\\',false, \\'" . $elmLargeImage . "\\');\">";
                        $strImagesLarge .= '<img style="vertical-align:top; margin: 0 0 4px 4px;" border="0" width="65" src="' . $path . 'small/' . $imageLarge .'"></a>';
                    }
                }
                $this->view->strImagesLarge = $strImagesLarge . '<div style="clear:both;height:0px;">&nbsp;</div>';

                if(!empty($videoFiles) && is_array($videoFiles)){
                    $configVideo = $this->_model->selectConfigForVideo();
                    $videoWidth = $configVideo['video_width']['value'];
                    $videoHeight = $configVideo['video_height']['value'];

                    foreach ($videoFiles as $file){
                        $view = new Zend_View();
                        $view->setScriptPath($this->_config->website->website->path . 'application/views/scripts/generator/');
                        $view->path = $path;
                        $view->file = $file;
                        
                        if(preg_match("/\.(avi|mov|mp4|swf|flv|mpeg|wmv|mpg)$/", $file, $matches)){
                            $view->fileType = $matches[1];
                        }
                        $view->videoWidth = $videoWidth;
                        $view->videoHeight = $videoHeight;
                        $view->webSiteUrl = $this->_config->website->website->url;
                        $htmlElm = $view->render('videotemplate.phtml');
                        $strVideo .= '<p style="text-align:left;font-size:12px;font-weight: normal;margin: 4px 0px 4px 0px;"><a style="color:#999;font-size:12px;" href="javascript:;" onmousedown="$(&#39#' . $textareaId . '&#39).tinymce().execCommand(&#39mceInsertContent&#39,false,&#39;' . htmlspecialchars($htmlElm) . '&#39;);">' . $file . '</a></p>';
                    }
                }
            $this->view->strVideo = $strVideo . '<div style="clear:both;height:0px;">&nbsp;</div>';
        }
    }

    /**
     * This function loads images for removethings.
     * @return void
     */
    public function loadimagesforremovethingsAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()){
            $folder = trim($this->getRequest()->getParam('folder'));
            if($folder !== '' && is_dir($this->_config->website->website->path . $this->_config->website->website->images . $folder) ){
                $path = $this->view->websiteUrl . 'images/' . $folder . '/small/';
                $response = '';
                $images = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');

                if(!empty($images) && is_array($images)){
                    foreach($images as $image){
                        $response .= "<div align=\"center\" id=\"removethings_one_image\">\n";
                        $response .= "<img alt=\"" . Default_View_Helper_ToolsHelper::cropType($image) . "\" title=\"" . $image . "\" border=\"0\" width=\"65\" src=\"" . $path . $image . "\">\n";
                        $response .= "<input type=\"checkbox\" name=\"images[" . $image ."]\">\n";
                        $response .= "</div>\n";
                    }
                }
                $videoPath = $this->_config->website->website->path . $this->_config->website->website->images . $folder . '/video/' ;
                $videoFiles = RCMS_Tools_FilesystemTools::scanDir($videoPath);

                if(!empty($videoFiles) && is_array($videoFiles)){
                    $response .= "<div style=\"clear:both;margin:5px auto 5px auto;text-align:center;background-color:#eee;\">Videos</div>\n";
                    foreach ($videoFiles as $videoFile){
                        $response .= "<div align=\"center\" style=\"height:100px;\" id=\"removethings_one_image\">\n";
                        $response .= "<img alt=\"" . Default_View_Helper_ToolsHelper::cropType($videoFile) . "\" title=\"" . $videoFile . "\" border=\"0\" width=\"65\" src=\"" . $this->_config->website->website->url . "system/images/ico_video.gif\">\n";
                        $response .= "<span style=\"font-size:9px;font-weight: normal;\">".$videoFile."</span><input type=\"checkbox\" name=\"videos[" . $videoFile ."]\" />\n";
                        $response .= "</div>\n" ;
                    }
                }
                echo $response;
            }
        }
    }

    /**
     * This function deletes tempalte.
     * @return void
     */
    public function deletetemplateAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()){
            $templateId= (int)$this->getRequest()->getParam('id');
            $templateObj = new RCMS_Object_Template_Template($templateId);
            $resultDeleteTemplate = $templateObj->delete();
            $pageObj = new RCMS_Object_Page_Page();
            $pageObj->resetToDefaultTemplate($templateId);
            $result = $templateObj->getTemplateByName('default');
            echo $result->id;
        }
    }

    /**
     * This function saves settings for gallery.
     * @return void
     */
    public function savesettingsforgalleryAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != ''){
            $path = $this->_config->website->website->path . $this->_config->website->website->galleries;
            $gallery = $this->getRequest()->getParam('gallery');
            if(file_exists($path . $gallery .'/settings.txt') && is_dir($path . $gallery )){
                $settings = $this->getRequest()->getParam('thumbnails') . ':';
                $settings .= ($this->getRequest()->getParam('crop')=='true'?'1':'0') . ':';
                $settings .= ($this->getRequest()->getParam('lightbox')=='true'?'1':'0') . ':';
                $settings .= ($this->getRequest()->getParam('caption')=='true'?'1':'0');
                @file_put_contents($path . $gallery .'/settings.txt', $settings);
                echo json_encode(array('save' => true, 'new_gallery' => false)); exit;
            } else {
                $gallery = RCMS_Tools_FilesystemTools::validateName($gallery);
                RCMS_Tools_FilesystemTools::mkDir($path . $gallery);
                RCMS_Tools_FilesystemTools::mkDir($path . $gallery . '/thumbnails/');
                $settings = $this->getRequest()->getParam('thumbnails') . ':';
                $settings .= ($this->getRequest()->getParam('crop')=='true'?'1':'0') . ':';
                $settings .= ($this->getRequest()->getParam('lightbox')=='true'?'1':'0') . ':';
                $settings .= ($this->getRequest()->getParam('caption')=='true'?'1':'0');
                @file_put_contents($path . $gallery .'/settings.txt', $settings);
                echo json_encode(array('save' => true, 'new_gallery' => true, 'gallery' => $gallery)); exit;
            }
        }
    }

    /**
     * This function loads settings for gallery.
     * @return void
     */
    public function loadsettingsforgalleryAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != ''){
            $path = $this->_config->website->website->path . $this->_config->website->website->galleries;
            $gallery = $this->getRequest()->getParam('gallery');
            if(file_exists($path . $gallery .'/settings.txt')){
                $settings = @file_get_contents($path . $gallery .'/settings.txt');
                $array = explode(':', $settings);
                echo json_encode(array(
                        'thumbnails'    => $array[0],
                        'crop'          => $array[1],
                        'lightbox'      => $array[2],
                        'caption'       => $array[3]
                )); exit;
            }
        }
    }

    /**
     * This function deletes picture in gallery.
     * @return Void
     */
    public function deletepictureingalleryAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('gallery') != '' && $this->getRequest()->getParam('image') != ''){
            $path = $this->_config->website->website->path . $this->_config->website->website->galleries;
            $gallery = $this->getRequest()->getParam('gallery');
            $image = $this->getRequest()->getParam('image');

            if(is_dir($path . $gallery) && file_exists($path . $gallery . '/' . $image)){
                RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/' . $image);
                RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/thumbnails/' . $image);
                $listImages = RCMS_Tools_FilesystemTools::scanDir($path . $gallery . '/thumbnails/');
                $deleteFolder = false;
                if(empty($listImages)){
                        RCMS_Tools_FilesystemTools::deleteFile($path . $gallery . '/settings.txt');
                        RCMS_Tools_FilesystemTools::rmDir($path . $gallery . '/thumbnails/');
                        RCMS_Tools_FilesystemTools::rmDir($path . $gallery);
                        $deleteFolder = true;
                }
                echo json_encode(array('del' => true, 'delete_folder' => $deleteFolder));
            }
            exit;
        }
    }

    /**
     * This function validates captcha.
     * @return boolean
     */
    private function validateCaptcha($captchaInput,$captchaId)
    {
        $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaId);
        $captchaIterator = $captchaSession->getIterator();
        $captchaWord = (isset($captchaIterator['word'])? $captchaIterator['word']:'');
        if( $captchaWord ){
            if( $captchaInput != $captchaWord ){
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * This function generates captcha.
     * @return integer
     */
    private function generateCaptcha()
    {
        $sitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
        $captcha = new Zend_Captcha_Image();
        $captcha->setTimeout('300')
                ->setWordLen('3')
                ->setHeight('50')
                ->setFont($sitePath.'public/system/fonts/times.ttf')
                ->setImgDir($sitePath.'public/tmp');
        $captcha->setDotNoiseLevel(0);
        $captcha->generate();    //command to generate session + create image
        return $captcha->getId();   //returns the ID given to session &amp; image
    }

    /**
     * This function inserts payment button.
     * @return void
     */
    public function insertpaymentbuttonincontentAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('name') != '' && $this->getRequest()->getParam('content') != ''){
            $name = trim(str_replace(' ', '-', $this->getRequest()->getParam('name')));
            $content = trim($this->getRequest()->getParam('content'));
            $content = preg_replace("~(<script.*>.*</script>)~s", '', $content);
            $ifExisted = (integer) $this->_model->selectIfExistPaymentButtonByName($name);

            if($ifExisted == 1) {
                $this->_model->updatePaymentButton($name, $content);
                echo json_encode(array('update' => true, 'name' => $name)); exit;
            }

            if($ifExisted == 0) {
                $this->_model->insertPaymentButton($name, $content);
                echo json_encode(array('update' => false, 'name' => $name)); exit;
            }
        }
    }

    /**
     * This function loads payment button.
     * @return void
     */
    public function loadpaymentbuttonbynameAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('name') != '') {
            $name = $this->getRequest()->getParam('name');
            $data = $this->_model->selectContentPaymentButtonByName($name);
            echo json_encode(array('content' => $data[0]['value'])); exit;
        }
    }

    /**
     * This function inserts comment.
     * @return void
     */
    public function insertcommentincontentAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('topic') != '' && $this->getRequest()->getParam('keyword') != '') {
            $topic = $this->getRequest()->getParam('topic');
            $keyword = $this->getRequest()->getParam('keyword');
            $ifExist = intval($this->_model->selectIfExistTopicAndKeyword($topic, $keyword));
            echo json_encode(array('exist' => $ifExist)); exit;
        }
    }

    /**
     * This function adds a redirect.
     * @return void
     */
     public function addredirectAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
            $this->getRequest()->getParam('topic');
            $originalOldUrl = $this->getRequest()->getParam('oldUrl');
            if(isset($originalOldUrl) && $originalOldUrl != ''){
                $originalOldUrl = str_replace(' ', '', trim($originalOldUrl));
            }

			$manualUrl = $this->getRequest()->getParam('manualurl');

			if(trim($manualUrl)==""){
			$pageId = $this->getRequest()->getParam('pageId');
            $pageObj = new RCMS_Object_Page_Page($pageId);
			}else
			{
				  $pageObj = new RCMS_Object_Page_Page();
				  $pageObj->setId(rand(10000,999999999));
				   $http = substr($manualUrl, 0,7);
					if(trim($http) != 'http://') {
						$manualUrl = 'http://' . $manualUrl;
					}
				  $pageObj->setUrl($manualUrl);
			}


            $http = substr($originalOldUrl, 0,7);
            if(trim($http) != 'http://') {
                $originalOldUrl = 'http://' . $originalOldUrl;
            }
            if($originalOldUrl == $this->_websiteUrl || $originalOldUrl . '/' == $this->_websiteUrl) {
                echo 'equal urls'; exit();
            }
            $tmp = $this->processDash($originalOldUrl);
            $res = explode('/', $tmp);
            $oneWord = $res[2];
            $res = explode($res[2], $tmp);
            if($res[1] != '') {
                $neededUrl = substr($res[1],1);
            }else {
                $neededUrl =  $oneWord;
            }
            $oldUrlProcessed = str_replace(' ', '', $neededUrl);
            $originalOldUrl = $this->processDash($originalOldUrl);
            if(!$this->_model->checkExistedRedirect($originalOldUrl)) {
                $oldUrlProcessed = str_replace(".", "\.", $oldUrlProcessed);
                $this->_model->insertRedirect($oldUrlProcessed, $originalOldUrl, $pageObj);
                $this->_seoParser->cleanBadRedirect($pageObj->getUrl() . '\.html');
				$result = '<div class="redirbord" id="redirect-'.$pageObj->getId().'" >';
				$result .=  '<div class="checkboxes"><input type="checkbox" id="'.$pageObj->getId().'" /></div>';
                $result .=  '<div class="redirecturl">';
                $result.=  $this->divideStringOnParts(urldecode(urldecode($originalOldUrl)));
                $result.=  '<span>&rarr;</span></div>';
                $result.= '<div class="redirecturlimg">';

				$tmp  =  strstr($pageObj->getUrl(), "http://");
				if($tmp!=false)
				{
					$newUrl  = $this->divideStringOnParts(urldecode(urldecode($pageObj->getUrl())));
				}else
				{
					$newUrl  = $this->divideStringOnParts(urldecode(urldecode($this->_websiteUrl.$pageObj->getUrl().".html")));
				}
                $result.= $newUrl;
                $result.= '<a href="javascript:void(0);" title="Delete redirect." onclick="deleteRedirect(';
                $result.= $pageObj->getId();
                $result.= ');"><img src="';
                $result.= $this->_websiteUrl;
                $result.= 'system/images/ico_delete.gif" alt="Delete"/></a></div>';
                $result.= '<p style="clear:both;"></p>';
                $result.= '</div>';
                echo $result;
            }else {
                echo 'exists';
            }
            $this->_seoParser->refreshHtAccess();
        }
    }

    /**
     * This function adds a deeplink.
     * @return void
     */
    public function adddeeplinkAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

            if($this->getRequest()->isPost()) {
                $name = trim(strip_tags($this->getRequest()->getParam('name')));
                $url = trim(strip_tags($this->getRequest()->getParam('url')));
                $result = $this->_validateDeeplink($name, $url);

                if(empty($result)) {
                    $ifExistName = (integer) $this->_model->selectDeeplinkByName($name);
                    if($ifExistName) {
                        echo 'exists';
                        return;
                    }
                } else {
                    switch ($result) {
                        case 'empty url':
                            echo 'empty url';
                            break;
                        case 'anchor only letters':
                            echo 'anchor only letters';
                            break;
                        case 'anchor at least 2 letters':
                            echo 'anchor at least 2 letters';
                            break;
                        case 'invalid url':
                            echo 'invalid url';
                            break;
                    }
                    return;
                }
                $http = substr($url, 0,7);
                
                if(trim($http) != 'http://') {
                    $url = 'http://' . $url;
                }
                $res = explode('/', $url);
                $arr = $res[sizeof($res)-1];
                $page = explode('.', $arr);
                $page = $page[0];
                
                if(trim($page) == '') {
                    echo 'page error';
                    return;
                }
                $deeplink = new RCMS_Object_Deeplink_Deeplink();
                $deeplink->setName($name);
                $deeplink->setUrl($url);
                $deeplink->setType($this->getRequest()->getParam('type'));
                $deeplink->setBan(0);
                $deeplink->setNoFollow($this->getRequest()->getParam('nofollow'));
                $flag = $deeplink->save();

                if($flag > 0) {
                    $seoParser = new RCMS_Object_Parser_SeoParser();
                    $seoParser->replaceDeeplinksInContent();

                    $result = '<div class="mandeepl" style="clear:both;" id="mandeepl-'.$flag.'">';
                    $result .= '<div class="mandeepname"><a title="Edit this deeplink" href="javascript:void(0);"';
                    $result .= ' onclick="fiilDeeplinkForm('.$flag.');" ';
                    $result .= '>'.$this->divideStringOnParts($deeplink->getName(),35).'</a></div>';
                    $result .= '<div class="mandeepu"><a title="Jump to URL" href="';
                    $result .= $deeplink->getUrl();
                    $result .= '" target="_blank">'.$this->divideStringOnParts(urldecode($deeplink->getUrl()),35).'</a></div>';
                    $result .= '<div class="mandeepthree">';
                    $result .= '<span>';
                    if($deeplink->getNoFollow()==1) {
                            $result .= 'NF';
                    }else {
                            $result .= 'F';
                    }
                    $result .= '</span>';
                    $result .= '<span>'.ucfirst($deeplink->getType()).'</span>';
                    $result .= '<span><img onclick="deleteDeeplink('.$flag.');" src="'.$this->_websiteUrl.'system/images/ico_delete.gif" title="Delete this deeplink" alt="ico-delete" style="cursor: pointer;"/></span>';
                    $result .= '</div>';
                    $result .= '<p style="clear:both;"></p>';
                    $result .= '</div>';
                    echo $result;
                }
            }
    }

    /**
     * This function fiils deeplink form.
     * @return void
     */
    public function fiildeeplinkformAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id')) {
            $deeplinkObj = new RCMS_Object_Deeplink_Deeplink($this->getRequest()->getParam('id'));
            $tmp = explode('/', $deeplinkObj->getUrl());
            $sizeTmp = sizeof($tmp);
            $p = $tmp[$sizeTmp-1];
            $tmpUrl = explode('.', $p);
            $tmpUrl = urlencode($tmpUrl[0]);
            $page = $this->_model->getPageByUrl($tmpUrl);
            echo $deeplinkObj->getId() . '~' . $deeplinkObj->getName() . '~' . $page['nav_name'] . '~' . $deeplinkObj->getType() . '~' . $deeplinkObj->getNoFollow() . '~' . $deeplinkObj->getUrl();
        }
    }

    /**
     * This function deletes deeplink.
     * @return void
     */
    public function editdeeplinkAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
            $id = intval($this->getRequest()->getParam('id'));
            $deeplinkObj = new RCMS_Object_Deeplink_Deeplink($id);
            $name = trim(strip_tags($this->getRequest()->getParam('name')));
            $url = trim(strip_tags($this->getRequest()->getParam('url')));
            $http = substr($url, 0,7);

            if(trim($http) != 'http://') {
                $url = 'http://' . $url;
            }
            $res = explode('/', $url);
            $arr = $res[sizeof($res)-1];
            $page = explode('.', $arr);
            $page = $page[0];

            if(trim($page) == '') {
                echo 'page error';
                return;
            }
            $result = $this->_validateDeeplink($name, $url);

            if(empty($result)) {
                $ifExistName = (integer) $this->_model->selectDeeplinkByName($name);
                if($ifExistName > 0 && $name!=$deeplinkObj->getName() ) {
                    echo 'exists';
                    return;
                }
            } else {
                switch ($result) {
                    case 'empty url':
                            echo 'empty url';
                            break;
                    case 'anchor only letters':
                            echo 'anchor only letters';
                            break;
                    case 'anchor at least 2 letters':
                            echo 'anchor at least 2 letters';
                            break;
                    case 'invalid url':
                            echo 'invalid url';
                            break;
                }
                return;
            }
            $deeplinkObj->setName($name);
            $deeplinkObj->setType($this->getRequest()->getParam('type'));
            $deeplinkObj->setUrl($url);
            $deeplinkObj->setNoFollow($this->getRequest()->getParam('nofollow'));
            $deeplinkObj->setBan(0);
            $flag =  $deeplinkObj->save();

            if($flag > 0) {
                $seoParser = new RCMS_Object_Parser_SeoParser();
                $seoParser->replaceDeeplinksInContent();
            }
            $result = $deeplinkObj->getId()."~";
            $result .= '<div class="mandeepname"><a title="Edit this deeplink" href="javascript:void(0);"';
            $result .= ' onclick="fiilDeeplinkForm('.$deeplinkObj->getId().');" ';
            $result .= '>'.$this->divideStringOnParts($deeplinkObj->getName(),35).'</a></div>';
            $result .= '<div class="mandeepu"><a title="Jump to URL" href="';
            $result .= $deeplinkObj->getUrl();
            $result .= '" target="_blank">'.$this->divideStringOnParts($deeplinkObj->getUrl(),35).'</a></div>';
            $result .= '<div class="mandeepthree">';
            $result .= '<span>';
            
            if($deeplinkObj->getNoFollow() == 1) {
                $result .= 'NF';
            } else {
                $result .= 'F';
            }
            $result .= '</span>';
            $result .= '<span>'.ucfirst($deeplinkObj->getType()).'</span>';
            $result .= '<span><img onclick="deleteDeeplink('.$deeplinkObj->getId().');" src="'.$this->_websiteUrl.'system/images/ico_delete.gif" title="Delete this deeplink" alt="ico-delete" style="cursor: pointer;"/></span>';
            $result .= '</div>';
            $result .= '<p style="clear:both;"></p>';
            echo $result;
        }
    }

    /**
     * This function deletes deeplink.
     * @return void
     */
    public function  deletedeeplinkAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id')) {
            $id = intval($this->getRequest()->getParam('id'));
            if($id > 0) {
                $seo = new RCMS_Object_Parser_SeoParser();
                $seo->deleteDeeplinkFromContent($id);
                $deeplink = new RCMS_Object_Deeplink_Deeplink($id);
                $deeplink->delete();
                echo $id; exit();
            }
        }
    }

    /**
     * Deletes redirect.
     * @return void
     */
    public function deleteredirectAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
            $pageId = $this->getRequest()->getParam('pageId');
            if($pageId) {
                $this->_model->deleteRedirect($pageId);
                echo $pageId;
            }
            $seoParser = new RCMS_Object_Parser_SeoParser();
            $seoParser->refreshHtAccess();
        }
    }
   /**
     * Deletes redirects.
     * @return void
     */
    public function deletemassredirectsAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
			$result = array();
            $arrIds = $this->getRequest()->getParam('arrIds');
			$arrIds = json_decode($arrIds);

            if($arrIds) {
				foreach ($arrIds as $key=>$value)
				{
					if($value)
					{
						$this->_model->deleteRedirect($value);
						$result[]=$value;
					}
				}
            }
			echo json_encode($result);
            $seoParser = new RCMS_Object_Parser_SeoParser();
            $seoParser->refreshHtAccess();

        }
    }
    /**
     * This functin returns array of vars.
     * @return void
     */
    public function getvarsAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $varrialbes = $this->_model->getAdditionalVarriablesNames();
        //check if rrs feeds exists. If yes create a variables for them
        $rssFeedVars = $this->_getRssFeedsList();
        if(!empty ($rssFeedVars)) {
                $varrialbes = array_merge($varrialbes, $rssFeedVars);
        }
        if(empty($varrialbes)) {
                echo 'no_vars';
                exit;
        }
        echo json_encode($varrialbes);
    }

    /**
     * This function devides string on parts of setted length.
     * @param string $string
     * @param integer $length
     * @return string
     */
    public function divideStringOnParts($string, $length = 50)
    {
       /* $result = '';
        $partsCount = (int)(strlen($string)/$length);
        for($i=0;$i<$partsCount+1;$i++) {
			//$result .= substr($string,($i*$length),$i+$length) . '<br/>';
            $result .= substr($string,($i*$length),$i+$length) . "<br>";
        }
        $end = sizeof($result)-6;
        $result = substr($result, 0,$end);
        return $result;*/
		 return $string;
    }

    /**
     * This function returns array of Rss List.
     * @return array
     */
    private function _getRssFeedsList()
    {
        $xmlFilesListVars = array();
        $tmpXmlFilesList = RCMS_Tools_FilesystemTools::findFilesByExt('../public', 'xml');
        foreach ($tmpXmlFilesList as $xmlFile) {
            if(stristr($xmlFile, 'sitemap') || stristr($xmlFile, 'sitemapnews') || stristr($xmlFile, 'sitemapindex')) {
                    continue;
            }
            $xmlFilesListVars[] = 'rssfeed:' . str_replace('.xml', '', $xmlFile);
			if(!stristr($xmlFile, 'full')) {
				$xmlFilesListVars[] = 'newslist:' . str_replace('.xml', '', $xmlFile);
			}
        }
        return $xmlFilesListVars;
    }

    /**
     * This functin is validate name and url.
     * @param string $name
     * @param string $url
     * @return array
     */
    private function _validateDeeplink($name, $url)
    {
        $url = str_replace('http://', '', $url);
        $url = str_replace('https://', '', $url);
        $url = str_replace('http:/', '', $url);
        $url = str_replace('https:/', '', $url);

        if($url === '') {
                return 'empty url';
        }
        if(!preg_match('/^[\p{L}\p{M}\p{P}A-z\s]{1,255}+$/u', $name)) {
                return 'anchor only letters';
        }
        if (!preg_match('/^[\p{L}\p{M}\p{P}a-z0-9-.\/]{1,210}+$/u', $url)) {
                return 'invalid url';
        }
    }
    /**
     * Deletes user.
     * @return void
     */
    public function deleteuserAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') > 0 ) {
            $user = new RCMS_Object_User_User($this->getRequest()->getParam('id'));
            if(is_object($user) && $user->getId() > 0) {
                $done = $user->delete(); echo $done;
            } else {
                echo '0';
            }
        }
        exit;
    }

    /**
     * Loads user.
     * @return void
     */
    public function loaduserAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') > 0 ) {
                $user = new RCMS_Object_User_User($this->getRequest()->getParam('id'));
                if(is_object($user) && $user->getId() > 0) {
                    echo json_encode(array(
                    'nickname'  => $user->getNickName(),
                    'login'     => $user->getLogin(),
                    'password'  => $user->getPassword(),
                    'email'     => $user->getEmail(),
                    'role'      => $user->getRoleId())
                    );
                } else {
                    echo json_encode(array());
                }
        }
        exit;
    }

    /**
     * Replaces '///' to '//'
     * @param string $string
     * @return string
     */
    public function processDash($str)
    {
        $pos = strstr($str, '///');
        if($pos) {
            return  $this->processDash(str_replace('///', '//', $str));
        }
        return $str;
    }

    /**
     * Run Google wheel to find a sinonyms.
     * @return void
     */
    public function rungooglewheelAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if($this->getRequest()->isPost()) {
            $inspWord = urlencode(strip_tags($this->getRequest()->getParam('inspired')));
            $firstWheelSearchUrl = 'http://www.google.com/search?q=' . $inspWord . '&hl=en&tbo=1&tbs=ww:1';
            $result = $this->_runCurlForWheel($firstWheelSearchUrl);
                if($result) {
                    if (preg_match('/"r":\[(.*?)\]}\)/', $result, $matches)) {
                        $response = str_replace('"', '', $matches[1]);
                        $secondResponse = explode(',', $response);
                        $thirdResponse = '';
                        foreach ($secondResponse as $key => $value) {
                            $encodedValue = urlencode($value);
                            $secondWheelSearchUrl = 'http://www.google.com/search?q=' . $encodedValue . '&hl=en&tbo=1&tbs=ww:1';
                            $secondResult = $this->_runCurlForWheel($secondWheelSearchUrl);
                            if($secondResult) {
                                if (preg_match('/"r":\[(.*?)\]}\)/', $secondResult, $matches2)) {
                                        $response .= ',' . str_replace('"','',$matches2[1]);
                                }
                            }
                        }
                        $thirdResponse = array_unique(explode(',', $response));
                        asort($thirdResponse);
                        $finalResult = '<span>Google wheel is answering:</span><br/><br/><ul class="whole-phrase">';
                        foreach ($thirdResponse as $key => $value) {
                            $finalResult .= '<li>'.utf8_decode($value).'</li>';
                        }
                        $finalResult.='</ul>';
                    }
                }
            echo $finalResult;
        }
        exit;
    }

    /**
     * Execute curl for google wheel.
     * @param string $searchUrl
     * @return string
     */
    private function _runCurlForWheel($searchUrl)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $searchUrl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_REFERER, $searchUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    ////////////////**********Form Hadling**************//////////////////////////////////
    /**
     * This function generates email body for auto reply message.
     * @param array $post
     * @param RCMS_Object_Page_Page $pageObj
     * @return string
     */
    private function _generateFormEmaiToAdminBody($post, RCMS_Object_Page_Page $pageObj)
    {
        $body = '\n New message posted on ' . $this->getWebSiteUrl().$pageObj->getUrl() . '.html . \n';

        $content = '';
        if($post) {
            foreach($post as $key=>$value) {
                if(trim($key)!='controller' && trim($key)!='action' && trim($key)!='module' && trim($key)!='pageId' && trim($key)!='formId' && trim($key)!='captchaId' && trim($key)!='captcha' && trim($key)!='input' && trim($key)!=trim($value)) {
                    $content .= trim($key) . ' : ' . (($value)? trim($value) : 'empty.') . "\n";
                }
            }
        }
        return $body.$content;
    }


    /**
     * This function generates email body for auto reply message
     * @param  RCMS_Object_Form_Form $formObj
     * @return string
     */
    private function _generateFormEmaiAutoReplyBody(RCMS_Object_Form_Form $formObj=null)
    {
            if($formObj!=null && $formObj->getEmailMessage()) {
                return $formObj->getEmailMessage();
            } else {
                return 'Thank you for posting a message.';
            }
    }

    /**
     * @method This function checks if smtp allowed in config
     * @return Boolean
     */
    private function _checkSmtpAllowedInConfig() {
        if(isset($this->_configTableArray['use_smtp']) && $this->_configTableArray['use_smtp'] == 1 &&
                isset($this->_configTableArray['smtp_login']) && $this->_configTableArray['smtp_login'] != '' &&
                isset($this->_configTableArray['smtp_password']) && $this->_configTableArray['smtp_password'] != '') {
                return true;
        }
        return false;
    }

    /**
     * This function checks if smtp allowed in Form Object
     * @param RCMS_Object_Form_Form $formObj
     * @return boolean
     */
    private function _checkSmtpAllowedInFormObj(RCMS_Object_Form_Form $formObj)
    {
        if($formObj->getUseSMTP()){
            return true;
        }
        return false;
    }


    /**
     * This function returns email to FORM settings.
     * @param RCMS_Object_Form_Form $formObj
     * @return string
     */
    private function _getEmailTo(RCMS_Object_Form_Form $formObj=null)
    {
        if($formObj!=null) {
            if($formObj->getEmail()) {
                return $formObj->getEmail();
            }
                return $this->_adminEmail;
        }else {
            return $this->_adminEmail;
        }

    }

    /**
     * This function returns email from FORM settings.
     * @param RCMS_Object_Form_Form $formObj
     * @return string
     **/
    private function _getEmailFrom(RCMS_Object_Form_Form $formObj)
    {
        if($formObj != null) {
            if($formObj->getEmailFrom()) {
                    return $formObj->getEmailFrom();
            }
        }
        return false;
    }

    /**
     * @method This function put message in session and redirects to page
     * @return RCMS_Object_Form_Form $formObj
     * @return string $messageType
     * @return void
     **/
    private function _showEmailMessage(RCMS_Object_Form_Form $formObj,$messageType)
    {
        if($messageType == 'success') {
            if($formObj && trim($formObj->getSuccessMessage()) != '') {
                $successMessage = trim($formObj->getSuccessMessage());
            } else {
                $successMessage = 'Email was sent.';
            }
            $this->_session->formSuccessMessage = $successMessage;
        }
        if($messageType == 'error') {
            if(trim($formObj->getErrorMessage()) != '') {
                $errorMessage = trim($formObj->getErrorMessage());
            } else {
                $errorMessage = 'Sending failed. Check your SMTP settings.';
            }
            $this->_session->formErrorMessage = $errorMessage;
        }
        if($messageType == 'captcha') {
            $this->_session->formCaptchaNotValid = 'Captcha is not valid.';
        }
        if($messageType == 'smtp denied') {
            $this->_session->formSmtpMessage = 'Sending email failed.<br/> Check your smtp settings in manage config screen.';
        }
        if($messageType == 'email not valid') {
            $this->_session->formEmailNotValid = 'Entered Email is not valid.';
        }
        $this->_redirect($this->getWebSiteUrl().$this->_pageUrl);
        exit;
    }


    /**
     * @method This function generates value for to/from comment variable
     * @return string
     **/
    private function _generateSmtpComment($userName,$email)
    {
        if($userName) {
            return $userName;
        } else {
            $arr = explode('@', $email);
            return $arr[0];
        }
    }

/*!!!!!! THIS IS NOT FUNCTION FOR AJAX. !!!!!!!*/
    /**
     * @method This function handles form submit
     * @return void
     */
    public function formhandlerAction()
    {
        $this->_initSmtp();
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);


        if($this->getRequest()->isPost() && $this->getRequest()->getParam('formId') > 0 && $this->getRequest()->getParam('pageId') > 0 ) {
        //default case if we do not use captcha so we put it in true
            $captchaValid = true;
            $post = $this->getRequest()->getParams();
            $formObj = new RCMS_Object_Form_Form($this->getRequest()->getParam('formId'));
            $pageObj = new RCMS_Object_Page_Page($this->getRequest()->getParam('pageId'));
            $this->_pageUrl = $pageObj->getUrl() . '.html';
            //check if captcha set and valid
            if(isset($post['captchaId']) && $post['captchaId'] != '') {
                $captcha= $this->getRequest()->getParam('captcha');
                $captchaInput = $captcha['input'];
                $captchaId = $this->getRequest()->getParam('captchaId');

                if( !$this->validateCaptcha($captchaInput,$captchaId) ) {
                    $captchaValid = false;
                }
            }
            if($captchaValid) {
                if(isset($post['name']) && trim($post['name']) != '' ) {
                    $userName = trim($post['name']);
                } else {
                    $userName = false;
                }
                if(isset($post['email']) && trim($post['email']) != '') {
                    $emailFrom = $post['email'];
                    $validator = new Zend_Validate_EmailAddress();
                    if(!$validator->isValid($emailFrom)) {
                        $this->_showEmailMessage($formObj,'email not valid');
                    }
                } else {
                    $emailFrom = 'userwithnoemail@userwithnoemail.com';
                }
                ///////////////////////////////////////////////////////////////////////
                $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
                $useSmtpInForm = $this->_checkSmtpAllowedInFormObj($formObj);
                if($useSmtpInForm==1 && $useSmtpInConfig==0 ) {
                    $this->_showEmailMessage($formObj,'smtp denied');
                }
                if($useSmtpInConfig && $useSmtpInForm) {
                    $useSmtp = true;
                } else {
                    $useSmtp = false;
                }
                //sending email to admin
                $to = $this->_getEmailTo($formObj);
                $toComment = $this->_smtpHost;
                $from = $emailFrom;
                $fromComment =  $this->_generateSmtpComment($userName,$emailFrom);

                $subject = 'A new message was posted on ' . $this->_domain;
                $body =  $this->_generateFormEmaiToAdminBody($post,$pageObj);
                $emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
                /////////////////////////
                //sending auto reply message to user
                $to = $emailFrom;
                $toComment = $this->_generateSmtpComment($userName,$emailFrom);
                $from = $this->_getEmailFrom($formObj);
                $fromComment = $this->_smtpHost;
                $subject = 'A message from ' . $this->_smtpHost;
                $body =  $this->_generateFormEmaiAutoReplyBody($formObj);
                $emailAutoReplySent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);

                if($emailAdminSent) {
                    $this->_showEmailMessage($formObj,'success');
                } else {
                    $this->_showEmailMessage($formObj,'error');
                }
            } else {
                $this->_showEmailMessage($formObj,'captcha');
            }
        }
        $this->_redirect($this->getWebSiteUrl().$this->_pageUrl);
    }


    /**
     * @method This function sends email through smtp or regular email
     * @param String $to
     * @param String $toComment
     * @param String $from
     * @param String $fromComment
     * @param String $subject
     * @param String $body
     * @param Integer $useSmtp
     * @return Boolean
     */
    public function sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp)
    {
        if($useSmtp) {
            $tr = new Zend_Mail_Transport_Smtp($this->_smtpHost, $this->_smtpConfigArray);
            Zend_Mail::setDefaultTransport($tr);
            $mailer = new Zend_Mail( 'utf-8' );
            $mailer->addTo($to,$toComment);
            $mailer->setFrom($from,$fromComment);
            $mailer->setSubject($subject);
            $mailer->setBodyText($body);
            try {
                $mailer->send();
                return true;
            } catch (Exception $e) {
                return false;            
            }
        } else {
            $mailer = new Zend_Mail( 'utf-8' );
            $mailer->addTo($to,$toComment);
            $mailer->setFrom($from,$fromComment);
            $mailer->setSubject($subject);
            $mailer->setBodyText($body);
            try {
                $mailer->send();
                return true;
            } catch (Exception $e) {
                return false;            
            }
        }
    }

    ////////////////////*********COMMENTS HANDLER ACTION**************//////////////////////////////////
    /**
     * @method This function generates body of email to admin in order to inform that a new comment was added
     * @param <String> $sign
     * @param <String> $email
     * @param <String> $content
     * @return <String>
     */
    private function _generateEmailBodyForAdminComments($sign,$email,$content)
    {
        if($sign && $email && $content) {
            $sign = ucfirst(strtolower(trim($sign)));
            $email = trim($email);
            $content = trim($content);
            return 'Hello,  ' . $sign . "  '<".$email.">' posted a new comment on ".$this->getWebSiteUrl().$this->_pageUrl.". \n Please login to the system to moderate this comment. \r\n Message: \n".$content;
        }
        return '';
    }

    /**
     * @method This function generates body of email to users in order to inform them about a new comment on a subject metter
     * @param String $sign
     * @param String $email
     * @return String
     */
    private function _generateEmailBodyForNotifyComments($sign, $email)
    {
        return "---- No need to reply to this email. --- \n \n \n Hello,  ".$sign."  '<".$email.">', this is an automated message to inform you of a new comment posted on ".$this->_websiteUrl.$this->_pageUrl." \n\n\n---- No need to reply to this email. ---\n";
    }

    /**
     * @method This function generates body of email to user in order to inform him that his comment was published
     * @param RCMS_Object_Comment_Comment $commentObj
     * @return String
     */
    private function _generateEmailBodyForPublishingComment(RCMS_Object_Comment_Comment $commentObj)
    {
        return "---- No need to reply to this email. --- \n \n \n Hello,  ".$commentObj->getUserSign()."  '<".$commentObj->getUserEmail().">', this is an automated message to inform you that your comment was published on ".$this->_websiteUrl.$this->_pageUrl." \n\n\n---- No need to reply to this email. ---\n";
    }

    /**
     * @method This function adds new comment
     * @return Void
     */
    public function addcommentAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);        
        $this->_initSmtp();

        if($this->getRequest()->isPost() && $this->getRequest()->getParam('content') != ''
            && $this->getRequest()->getParam('sign') != '' && $this->getRequest()->getParam('email') != '') {
            $content = ($this->getRequest()->getParam('content'))? addslashes(htmlspecialchars($this->getRequest()->getParam('content'))) : '';
            $sign = ($this->getRequest()->getParam('sign'))? addslashes(htmlspecialchars($this->getRequest()->getParam('sign'))) : '';
            $email = ($this->getRequest()->getParam('email'))? addslashes(htmlspecialchars($this->getRequest()->getParam('email'))) : '';
            $website = ($this->getRequest()->getParam('website'))? addslashes(htmlspecialchars($this->getRequest()->getParam('website'))) : '';
            $containerId = ($this->getRequest()->getParam('containerId'))? $this->getRequest()->getParam('containerId') : 0;
            $topic = ($this->getRequest()->getParam('topic'))? addslashes($this->getRequest()->getParam('topic')) : '';
            $keyword = ($this->getRequest()->getParam('keyword'))? addslashes($this->getRequest()->getParam('keyword')) : '';
            $publishedbydefault = ($this->getRequest()->getParam('publishedbydefault'))? $this->getRequest()->getParam('publishedbydefault') : 0;
            $notify = ($this->getRequest()->getParam('notify'))? $this->getRequest()->getParam('notify') : 0;
            $captchaInput = addslashes(htmlspecialchars($this->getRequest()->getParam('captcha-input')));
            $captchaId = $this->getRequest()->getParam('captcha-id');
            $this->_pageUrl =  ($this->getRequest()->getParam('requestedPage'))? str_replace('.html', '', $this->getRequest()->getParam('requestedPage')) . '.html' : '';
            if($notify == 'true') {
                $notify =1;
            } else {
                $notify =0;
            }            
            if( !$this->validateCaptcha($captchaInput,$captchaId) ) {
                $captchaId = $this->generateCaptcha();
                echo 'captacha error~' . $sign . '~' . $email . '~' . $website . '~' . $notify . '~' . $content . '~' . $captchaId;
                exit();
            }
            $commentObj = new RCMS_Object_Comment_Comment();
            $commentObj->setContent($content);
            $commentObj->setConteinerId($containerId);
            $commentObj->setDate(date("Y-m-d H:i:s"));
            $commentObj->setUserId(0);
            $commentObj->setUserEmail($email);
            $commentObj->setAbuse(0);
            $commentObj->setUserSign($sign);
            $commentObj->setUserWebsite($website);
            $commentObj->setPublish($publishedbydefault);
            $commentObj->setRank(0);
            $commentObj->setTopic($topic);
            $commentObj->setKeyword($keyword);
            $commentObj->setNotify($notify);
            $result = false;
            $newCommentId = $commentObj->save();            
            $commentsToNotifyArray = $this->_model->selectCommentsToNotify($commentObj->getConteinerId());
            $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
            if($useSmtpInConfig) {
                $useSmtp = true;
            } else {
                $useSmtp = false;
            }
            $adminEmail = $this->_adminEmail;
            $to = $adminEmail;
            $toComment = $this->_smtpHost;
            $from = $commentObj->getUserEmail();
            $fromComment = $this->_smtpHost;
            $subject = 'A new comment was posted on ' . $this->_smtpHost;
            $body =  $this->_generateEmailBodyForAdminComments($sign,$email,$content);
            $emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);            
            if($commentsToNotifyArray) {
                foreach ($commentsToNotifyArray as $comment) {
                    $to = $comment['user_email'];
                    $toComment = $this->_smtpHost;
                    $from = $adminEmail;
                    $fromComment = $this->_smtpHost;
                    $subject = "A new comment was posted on ".$this->_smtpHost;
                    $body =  $this->_generateEmailBodyForNotifyComments($comment['user_sign'],$comment['user_email']);
                    $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);     
				}
            }
			$style = ($commentObj->getPublish()) ? 'style="border:1px solid #DDD;"' : 'style="border:1px dotted red"';
            if($newCommentId) {
                $result  = '<li '.$style.' id="comment-item-li-'.$newCommentId.'"> ';
                $result .= '<span class="username">';
                $result .=  ucfirst(strtolower($commentObj->getUserSign()));
                $result .= ' says:</span>';
                $result .= '<span class="commentdate">';
                $result .=  RCMS_Tools_Tools::proccessPublishingDateCommentsFromSql($commentObj->getDate());
                $result .= '</span>';
                $result .= ' <a class="commentreply" href="';
                $result .= $this->view->websiteUrl.$this->_pageUrl."#comment-form";
                $result .= '" title="Reply to this comment">Reply';
                $result .= '</a>';
                $result .= '<p class="commenttext">';
                $result .= $commentObj->getContent();
                $result .= '</p>';
                if($this->_session->isLogged) {
                    $result .= '<a class="deletecomment" title="Delete this comment" onclick="if(confirm(\'Do you really want to delete this comment?\')){deleteComment('.$newCommentId.'); } " href="javascript:void(0);" >';
                    $result .= '<img style="width:16px;border:none;" alt="Delete this comment" src="';
                    $result .= $this->view->websiteUrl.'system/images/ico_delete.gif"/>';
                    $result .= '</a>';
                }
                $result .= '</li>';
            }
            $captchaId = $this->generateCaptcha();
            echo $result . '~' . $captchaId;
        }
    }

    /**
     * @method This function deleting comment
     * @return Void
     */
    public function deletecommentAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') != '') {
            $commentId = $this->getRequest()->getParam('id');
            $commentObj = new RCMS_Object_Comment_Comment($commentId);
            if($commentObj->delete()) {
                echo 'Comment ' . $commentId . ' was deleted.';
            }
        }
    }

    /**
     * @method This function publishing commnet
     * @return Void
     */
    public function  publishcommentAction()
    {
        $this->_initSmtp();
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if($this->getRequest()->isPost() && $this->getRequest()->getParam('id') != '') {
            $commentId = $this->getRequest()->getParam('id');
            $commentObj = new RCMS_Object_Comment_Comment($commentId);
            $commentObj->setPublish(1);
            $commentObj->save();
            echo $commentId;
            $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
            if($useSmtpInConfig) {
                $useSmtp = true;
            } else {
                $useSmtp = false;
            }
            $adminEmail = $this->_adminEmail;
            $to = $commentObj->getUserEmail();
            $toComment = $commentObj->getUserSign();
            $from = $adminEmail;
            $fromComment = $this->_smtpHost;
            $subject = 'Your comment was published on ' . $this->_smtpHost;
            $body =  $this->_generateEmailBodyForPublishingComment($commentObj);
            $emailAdminSent = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
        }
    }

}
